import Home from '../views/Home';
import Detail from '../views/Detail';
import TodoService from '../services/Todo';
import TodoItem from '../components/TodoItem';

//负责将异步请求服务器返回的数据和字符串页面模版进行组装
export async function HomeView() {
  //请求异步数据
  const res = await TodoService.getTodoList();
  /**
   * console.log(res);
   * {
   *   msg: 'Get todoList successfully!',
   *   code: 0,
   *   data: [{_id: '6409d2d86f05761c0dbf0dc1', title: '111', content: '111', completed: false, createdAt: '2023-03-09T12:36:40.718Z', …}]
   * }
   */
  if (res.code === 0) {
    return Home(res.data);
  }
}

export async function DetailView(params) {
  const { id } = params; //6409d2d86f05761c0dbf0dc1
  const res = await TodoService.getTodo(id);
  if (res.code === 0) {
    return Detail(res.data);
  }
}

//页面脚本加载函数
export function homeScript() {
  const oApp = document.querySelector('#app');
  const oList = oApp.querySelector('#list');
  const oAddBtn = oApp.querySelector('.add-btn');
  const oTodoTitle = oApp.querySelector('.todo-title');
  const oTodoContent = oApp.querySelector('.todo-content');

  function handleListClick(e) {
    const tar = e.target;
    const className = tar.className;
    switch (className) {
      case 'toggle-check-box':
        handleCheckBoxClick(tar);
        break;
      case 'remove-btn':
        handleRemoveBtnClick(tar);
        break;
      default:
        break;
    }
  }

  async function handleAddBtnClick(e) {
    //获取输入框文本信息
    const title = oTodoTitle.value;
    const content = oTodoContent.value;
    if (!title.length || !content.length) return;
    const res = await TodoService.addTodo({ title, content });
    if (res.code === 0) {
      const listItem = TodoItem(res.data);
      oList.innerHTML += listItem;
    }
    oTodoTitle.value = '';
    oTodoContent.value = '';
  }

  async function handleCheckBoxClick(tar) {
    const id = tar.dataset.id;
    const res = await TodoService.toggleTodo(id);
    if (res.code === 0) {
      const oTitle = tar.parentNode.querySelector('a');
      oTitle.classList.toggle('completed');
    }
  }

  async function handleRemoveBtnClick(tar) {
    const id = tar.dataset.id;
    const res = await TodoService.removeTodo(id);
    if (res.code === 0) {
      tar.parentNode.remove();
    }
  }

  function bindEvent() {
    oAddBtn.addEventListener('click', handleAddBtnClick, false);
    oList.addEventListener('click', handleListClick, false);
  }
  bindEvent();
}

export function detailScript() {
  const oRemoveBtn = document.querySelector('#removeBtn');

  function bindEvent() {
    oRemoveBtn.addEventListener('click', handleRemoveBtnClick, false);
  }

  async function handleRemoveBtnClick(e) {
    const tar = e.target;
    const id = tar.dataset.id;
    const res = await TodoService.removeTodo(id);
    if (res.code === 0) {
      location.href = '/#/home';
    }
  }

  bindEvent();
}
